package weaver.ofs.interfaces;

import com.api.system.language.autoTranslate.MD5;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import weaver.conn.RecordSet;
import weaver.workflow.request.todo.RequestStatusObj;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;


/**
 * 本示例，只将接受的数据打印在log/ecology中，具体的接口调用操作，请在相关数据遍历中执行。
 * 实现weaver.ofs.interfaces.SendRequestStatusDataInterfaces接口中SendRequestStatusData
 */
public class SendJslytRequest {
    private static final Log log = LogFactory.getLog(SendJslytRequest.class);

    private String APP_SECRET = "e89277cb47e64f3d9473c401b559ff11";
    private String APP_ID = "d12733aa0b68498fa6e13e4843c171de";
    private String URL = "https://www.fjjslds.com";
    private String CODE = "S20250606001";
    private String DATA_CONTENT = "我在测试";


    private boolean IS_START = true; // 是否开始

    // 新增常量
    private String REMARK = "your_remark_value"; // 备注
    private String NOTE = "your_note_value"; // 信息说明
    //private String OPR_TYPE = "submit"; // 操作类型，可选值：stateRecall、closeprocess、revoke、forceEnd

    private String CATEGORY_ID = "dd00d4fa686f4f03936b968cb4402d62"; // 分类ID
    private String SYSTEM_CODE = "oa"; // 系统编号
    private String SYSTEM_NAME = "泛微OA系统"; // 系统名称

    public SendJslytRequest() {
    }

    /**
     * 发送消息请求
     *
     * @throws Exception
     */
    public void sendTodoRequest(RequestStatusObj rso ,JSONObject rsoJson) throws Exception {

        String token = getToken();
        //获取token值后，调用spi接口
        String url2 = URL + "/intf";
        //生成签名的参数
        Map<String, String> signParams = buildSignParams(rso,rsoJson);
        // 加入签名参数
        String sign2 = MD5.md5(mapSortToUrlParam(signParams, true));
        signParams.put("sign", sign2);
        // 将token放入请求头中
        Map<String, Object> head = buildHeaders(token);
        try {
            //发送请求
            log.info("流程ID:"+rso.getRequestid()+",开始调用推送消息接口...");
            log.info(signParams.toString());
            String result = postForm(url2, head, signParams);
            log.info(result);
            log.info("流程ID:"+rso.getRequestid()+",完成调用推送消息接口...");
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }


    /**
     * 发送消息请求
     *
     * @throws Exception
     */
    public void sendDelRequest(String piid) throws Exception {

        String token = getToken();
        //获取token值后，调用spi接口
        String url2 = URL + "/intf";
        //生成签名的参数
        long timestamp = new Date().getTime();
        // 加入签名参数
        Map<String, String> params = new HashMap<>();
        params.put("code","S20250606002");
        params.put("appSecret", APP_SECRET);
        params.put("timestamp", String.valueOf(timestamp));
        params.put("piid", piid);

        String sign2 = MD5.md5(mapSortToUrlParam(params, true));
        params.put("sign", sign2);
        // 将token放入请求头中
        Map<String, Object> head = buildHeaders(token);
        try {
            //发送请求
            log.info("开始删除待办消息...");
            String result = postForm(url2, head, params);
            log.info(result);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }

    private String getToken() throws Exception {
        //生成签名的参数
        Map<String, String> param1 = new HashMap<>();
        param1.put("appId", APP_ID);
        param1.put("appSecret", APP_SECRET);
        param1.put("timestamp", String.valueOf(new Date().getTime()));
        String param1str = mapSortToUrlParam(param1, true);
        String sign = MD5.md5(param1str);
        param1.put("sign", sign);
        String url1 = URL + "/spiToken";

        //获取token的返回结果
        String tokenresult = postForm(url1, null, param1);

        //解析结果中token[结果要判断，这里只是做个样例]
        JSONObject jsonObject = JSONObject.fromObject(tokenresult);

        String token = jsonObject.getString("data");
        log.info("获取到token:"+token);
        //[结果要判断，这里只是做个样例]
        return token;
    }

    private String getUsercodeByUid(int uid) {

        try {
            RecordSet recordSet = new RecordSet();
            String sql = "select textfield1 from hrmresource where id = '" + uid + "' ";

            recordSet.execute(sql);

            if (recordSet.next()) {
                // 从OA流程中提取参数
                String usercode = recordSet.getString("textfield1"); // 金盛兰云台用户编码
                // 记录返回结果
                //log.info("从手机号："+mobile+ " 获取的用户编码为："+usercode);
                if (StringUtils.isBlank(usercode)){
                    // 出错就按龙泽权的账号为已办人员
                    return "da7e1da96f5a459891dfd45ddee4f3a0";
                }
                return usercode;
            }
            // 出错就按龙泽权的账号为已办人员
            return "da7e1da96f5a459891dfd45ddee4f3a0";
        } catch (Exception e) {
            // 出错就按龙泽权的账号为已办人员
            return "da7e1da96f5a459891dfd45ddee4f3a0";
        }
    }

//    private String getUsercodeByMobile(String mobile) {
//        try {
//            RecordSet recordSet = new RecordSet();
//            String sql = "select textfield1 from hrmresource where mobile = '" + mobile + "' ";
//
//            recordSet.execute(sql);
//
//            if (recordSet.next()) {
//                // 从OA流程中提取参数
//                String usercode = recordSet.getString("textfield1"); // 金盛兰云台用户编码
//                // 记录返回结果
//                //log.info("从手机号："+mobile+ " 获取的用户编码为："+usercode);
//                if (StringUtils.isBlank(usercode)){
//                    // 出错就按龙泽权的账号为已办人员
//                    return "da7e1da96f5a459891dfd45ddee4f3a0";
//                }
//                return usercode;
//            }
//            // 出错就按龙泽权的账号为已办人员
//            return "da7e1da96f5a459891dfd45ddee4f3a0";
//        } catch (Exception e) {
//            // 出错就按龙泽权的账号为已办人员
//            return "da7e1da96f5a459891dfd45ddee4f3a0";
//        }
//    }


    /**
     * 签名生成函数
     *
     * @param map
     * @param allrowEmpty
     * @return
     */
    public String mapSortToUrlParam(Map<String, String> map, Boolean allrowEmpty) {
        List<String> keys = new ArrayList<>(map.keySet());
        Collections.sort(keys, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                // 返回相反的compare
                return o1.compareTo(o2);
            }
        });
        Iterator<String> iter = keys.iterator();
        StringBuffer signStr = new StringBuffer();
        while (iter.hasNext()) {
            String key = iter.next();
            Object value = map.get(key);
            if (!allrowEmpty && value == null) {// 不允许值为空
                continue;
            }
            if (signStr.length() > 0) {
                signStr.append("&");
            }
            signStr.append(key).append("=").append(value);
        }
        //System.out.println(signStr.toString());
        return signStr.toString();
    }

    /**
     * <p>Title: postForm</p>
     * <p>Description: 请求</p>
     *
     * @param url
     * @param headMap
     * @param params
     * @return
     * @throws Exception
     */
    public String postForm(String url, Map<String, Object> headMap, Map<String, String> params) throws Exception {
        try {
            // post请求
            HttpPost httpPost = new HttpPost(url);
            if (headMap != null && !headMap.isEmpty()) {// 头部
                for (String key : headMap.keySet()) {
                    httpPost.setHeader(key, headMap.get(key) != null ? headMap.get(key).toString() : "");
                }
            }
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            if (params != null && !params.isEmpty()) {
                for (String key : params.keySet()) {
                    nvps.add(new BasicNameValuePair(key, params.get(key) != null ? params.get(key).toString() : ""));
                }
            }
            httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
            int socketTimeout = 30000;
            int connectionTimeout = 30000;
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout)
                    .setConnectTimeout(connectionTimeout).build();// 设置请求和传输超时时间
            httpPost.setConfig(requestConfig);
            // 发送请求
            HttpClient httpclient = null;
            httpclient = HttpClientBuilder.create().build();
            HttpResponse httpresponse = httpclient.execute(httpPost);
            // 获取返回数据
            HttpEntity entity = httpresponse.getEntity();
            String body = EntityUtils.toString(entity, "UTF-8");
            return body;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }


    private Map<String, String> buildSignParams(RequestStatusObj rso,JSONObject rsoJson) {
        Map<String, String> params = new HashMap<>();
        params.put("code", CODE);
        params.put("appSecret", APP_SECRET);
        params.put("timestamp", String.valueOf(new Date().getTime()));
        params.put("data", DATA_CONTENT);
        //流程实例ID
        String requestid = String.valueOf(rso.getRequestid());
        params.put("piid", requestid);
        params.put("label", rso.getOfsPushId());
        // 流程名字
        String workflowname = rso.getWorkflowname();
        params.put("busiName", "[来自OA]" + workflowname);
        // 业务标题（流程标题）
        String docTitle = rso.getRequestnamenew();
        params.put("docTitle", docTitle);

        params.put("defineId", rso.getWorkflowid()+""); // 流程 ID（业务 ID）
        params.put("isStart", String.valueOf(IS_START)); // 是否开始
        // 是否结束
        if (rso.getIscomplete().equals("1")){
            params.put("isEnd", "true");
        }else {
            params.put("isEnd", "false");
        }
        params.put("applyName", rso.getCreator().getLastname()); // 申请人名称
        String applyCode = getUsercodeByUid(rso.getCreator().getUID());


        params.put("applyCode", applyCode); // 申请人编码
        params.put("applyTime", rso.getCreatedate() + "T" + rso.getCreatetime()); // 创建时间
        log.info("申请用户名称："+rso.getCreator().getLastname()+"，申请用户编码："+applyCode+"，申请用户id："+rso.getCreator().getUID());
        String passTaskId = (String)rsoJson.get("passTaskId");
        params.put("passTaskId", passTaskId); // 已办待办 ID
        String passActvName = (String)rsoJson.get("passActvName");
        params.put("passActvName", passActvName); // 已办环节名称
        int passUid =(int)rsoJson.get("passUid");
        String passUserCode = getUsercodeByUid(passUid);
        params.put("passUserCode", passUserCode); // 已办人员编号
        String passUserName = (String)rsoJson.get("passUserName");
        params.put("passUserName", passUserName); // 已办人员名称
        log.info("已办人员名称："+passUserName+"，已办人员编码："+passUserCode+"，passTaskId："+passTaskId+"，已办人员id："+passUid);
        params.put("remark", REMARK); // 备注
        params.put("note", NOTE); // 信息说明
        String oprType = (String)rsoJson.get("oprType");
        params.put("oprType", oprType); // 操作类型
        // 指派信息
        if (rso.getIsremark().equals("0")){
            params.put("assignArray", buildArray(rso,rsoJson));
        }else {
            params.put("assignArray", "[]");
        }


        String linkUrlIm = encodeUrl("https://oa.hbjinshenglan.com/spa/workflow/static4mobileform/index.html?#/req?requestid=" + requestid);
        params.put("linkUrlIm", linkUrlIm); // 移动端链接
        String linkUrlPc = encodeUrl("https://oa.hbjinshenglan.com/spa/workflow/static4form/index.html?#/main/workflow/req?requestid=" + requestid);
        params.put("linkUrlPc", linkUrlPc); // PC端链接
        params.put("categoryId", CATEGORY_ID); // 分类ID
        params.put("systemCode", SYSTEM_CODE); // 系统编号
        params.put("systemName", SYSTEM_NAME); // 系统名称
        log.info(params);
        return params;
    }

    public String encodeUrl(String str) {
        try {
            String prefix = "https://oa.hbjinshenglan.com/wui/sso/guide.html?targetUrl=";
            String encode = URLEncoder.encode(str, "UTF-8");
            return prefix + encode;
        } catch (UnsupportedEncodingException e) {
            return "https://oa.hbjinshenglan.com/spa/em/mobile.html";
        }
    }


    private Map<String, Object> buildHeaders(String token) {
        Map<String, Object> headers = new HashMap<>();
        headers.put("access_token", token);
        return headers;
    }

    private String buildArray(RequestStatusObj rso,JSONObject rsoJson) {
        List<Map<String, Object>> assignArray = new ArrayList<>();

        // 示例数据
        String[] actvNames = {rso.getNodename()};
        String usercode = getUsercodeByUid(rso.getUser().getUID());
        String[] userCodes = {usercode};
        String[] userNames = {rso.getUser().getLastname()};
        int msgInfoType ; // 消息类型
        if (rso.getIsremark().equals("0")){
            msgInfoType = 2; // 待办
        }else {
            msgInfoType = 1; // 提醒
        }

        for (int i = 0; i < actvNames.length; i++) {
            Map<String, Object> assignItem = new HashMap<>();
            assignItem.put("actvName", actvNames[i]);
            assignItem.put("taskId", (String)rsoJson.get("taskId"));
            assignItem.put("userCode", userCodes[i]);
            assignItem.put("userName", userNames[i]);
            assignItem.put("msgInfoType", msgInfoType);
            // 可选字段
            assignItem.put("remark", ""); // 如果有备注，替换为空字符串
            assignItem.put("note", "");   // 如果有注释信息，替换为空字符串
            log.info("待办人员名称："+userNames[i]+"，待办人员编码："+userCodes[i]+"，taskId："+rsoJson.get("taskId")+"，待办人员id："+rso.getUser().getUID());
            assignArray.add(assignItem);
        }

        // 使用Gson将列表转换为JSON字符串
        Gson gson = new Gson();
        String jsonString = gson.toJson(assignArray);

        return jsonString;
    }

}